package com.vilinno.tlias.filter;

import com.vilinno.tlias.utils.CurrentHolder;
import com.vilinno.tlias.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

//拦截请求
@WebFilter(urlPatterns = "/*")
@Slf4j
public class LoginFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("执行过滤器初始化方法");
    }

    /**
     * 按照流程图编写校验令牌的逻辑
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;

        log.info("拦截到了请求:{}",request.getHeaderNames());

        //1. 获取请求路径
        String url=request.getRequestURI();

        //2. 判断是否为登录请求，是则直接放行，否则继续处理
        if(url.contains("/login")){
            log.info("拦截到了登录请求，直接放行");
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        //3. 获取token
        String token=request.getHeader("token");

        //4. 校验token是否存在
        if(token==null || token.isEmpty()){
            log.info("令牌为空，响应401");
            response.setStatus(401);
            return;
        }

        //5.校验token是否正确
        try{
            Claims claims=JWTUtils.parseToken(token);
            Integer empId=Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(empId);
            log.info("当前登陆员工id为：{}",empId);
        }catch(Exception e){
            log.info("令牌非法，响应401");
            response.setStatus(401);
            return;
        }

        //6. token合法，放行请求
        log.info("token合法，放行请求");
        filterChain.doFilter(servletRequest,servletResponse);

        //7.删除threadLocal中的数据
        CurrentHolder.removeCurrentId();

    }

    @Override
    public void destroy() {
        log.info("执行过滤器析构方法");
    }
}
